To include tags and dates in your search, we need to update two things: the JSON index (to include the data) and the JavaScript logic (to search through that data).
1. Update the Search Index
We need to add tags and the raw date to your search.json. Update your search-index.json.njk file:
File: search-index.json.njk
Code snippet
---
permalink: /search.json
---
[
{% for post in collections.post %}
{
"title": {{ post.data.title | dump | safe }},
"url": {{ post.url | dump | safe }},
"date": "{{ post.date | postDate }}",
"tags": {{ post.data.tags | dump | safe }},
"searchContent": {{ (post.data.title + " " + post.data.tags | join(" ")) | lower | dump | safe }}
}{% if not loop.last %},{% endif %}
{% endfor %}
]
What changed? We added a searchContent field that combines the title and tags into one lowercase string, making the search logic much faster later.
---
2. Update the Search Logic (JavaScript)
Now, update the <script> tag in your layout.njk to check this new combined string. We will also make it search for the date string.
Replace the filter part of your script with this:
JavaScript
searchInput.addEventListener('input', (e) => {
const term = e.target.value.toLowerCase();
resultsList.innerHTML = '';
if (term.length < 2) {
resultsList.style.display = 'none';
return;
}
const filtered = posts.filter(post => {
// Search in our combined title/tags string OR the formatted date
return post.searchContent.includes(term) ||
post.date.toLowerCase().includes(term);
});
if (filtered.length > 0) {
resultsList.style.display = 'block';
filtered.forEach(post => {
const li = document.createElement('li');
// Clean up tags for display (optional)
const tagList = Array.isArray(post.tags)
? post.tags.filter(t => t !== 'post').join(', ')
: '';
li.innerHTML = `
<a href="${post.url}">${post.title}</a><br>
<small>${post.date} ${tagList ? 'in ' + tagList : ''}</small>
`;
resultsList.appendChild(li);
});
} else {
resultsList.style.display = 'block';
resultsList.innerHTML = '<li>No matches found</li>';
}
});
---
3. How the "Multi-Field" Search Works
By merging the metadata into a single string (searchContent) during the build phase, the user's browser doesn't have to do much work.
- If a user types "2026", it matches the date.
- If they type "webdev", it matches the tags.
- If they type "Hello", it matches the title.
4. Push and Test
Push these changes to GitHub. Once Cloudflare finishes building, try searching for a specific tag or a month name (like "February") to see the results update instantly.
Bash
git add .
git commit \-m "Enhance search to include tags and dates"
git push origin main
Now that your search is powerful, would you like to add an RSS feed so people can subscribe to your blog, or maybe some social media "Share" buttons at the bottom of your posts?